package com.sunmouse.toolkit.widget;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.ComposeShader;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.RadialGradient;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.View;

import com.sunmouse.toolkit.R;

/**
 * Created by Administrator on 2017/9/20 0020.
 */
public class DemoView extends View {
    private Paint mShaderPaint;
    private int w;
    private int h;

    public DemoView(Context context) {
        this(context, null);
    }

    public DemoView(Context context, AttributeSet attrs) {
        super(context, attrs);

        mShaderPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG);
        BitmapShader mShader= (BitmapShader) generateShader(1);
        Matrix mMatrix=new Matrix();
        mMatrix.setScale(0.3f,0.3f);
        mShader.setLocalMatrix(mMatrix);
        mShaderPaint.setShader(mShader);

        DisplayMetrics metrics = getResources().getDisplayMetrics();

        w = metrics.widthPixels;
        h = metrics.heightPixels;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //draw a round rectangle
//        canvas.drawRoundRect(w / 2 - 50, h / 2 - 50, w / 2 + 50, h / 2 + 50, 90, 90, mShaderPaint);
        canvas.drawCircle(getWidth() / 2, getHeight() / 2, 100, mShaderPaint);
    }


    /**
     * generate a shader
     *
     * @param i
     * @return
     */
    private Shader generateShader(int i) {
        switch (i) {
            case 1:
                Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.avatar);
                return new BitmapShader(mBitmap, Shader.TileMode.MIRROR, Shader.TileMode.REPEAT);
            case 2:
                return new LinearGradient(0, 0, w, h, Color.RED, Color.WHITE, Shader.TileMode.CLAMP);
            case 3:
                return new RadialGradient(w / 2, h / 2, w / 2, Color.RED, Color.WHITE, Shader.TileMode.CLAMP);
            case 4:
                return new SweepGradient(w / 2, h / 2, Color.RED, Color.WHITE);
            case 5:
                return new ComposeShader(generateShader(1), generateShader(3), PorterDuff.Mode.ADD);
        }

        return null;
    }
}
